package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * arr
 * leetcode 556. 下一个更大元素 III
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/12 17:56
 */
public class NextGreaterElement {
    public int nextGreaterElement(int n) {
        if (n < 12) {
            return -1;
        }
        String str = String.valueOf(n);
        int size = str.length();
        byte[] arr = str.getBytes();
        int index;

        for (int i = size - 2; i >= 0; i--) {
            int value = arr[i] - 48;
            index = size - 1;
            if (value < arr[i + 1] - 48) {
                while (arr[index] - 48 <= value) {
                    index--;
                }
                long v = 0;
                arr[i] = arr[index];
                arr[index] = (byte) (value + 48);
                for (int k = 0; k <= i; k++) {
                    v = v * 10 + arr[k] - 48;
                }
                for (int k = size - 1; k > i; k--) {
                    v = v * 10 + arr[k] - 48;
                }
                return v > Integer.MAX_VALUE ? -1 : (int) v;
            }
        }
        return -1;
    }
}
